package org.sample.commons.code;

import org.sample.commons.io.FileUtils;

import java.io.File;

public class MapperReplace {

    public static void replace(String entity, String mapperDir, String xmlDir) throws Exception {
        int count = 0;
        File[] mappers = new File(mapperDir).listFiles();
        File[] xmls = new File(xmlDir).listFiles();

        if (mappers.length != xmls.length)
            throw new RuntimeException();

        for (int i = 0; i < mappers.length; i++) {
            File mapper = mappers[i];
            File xml = xmls[i];

            String name = mapper.getName();
            Class<?> clazz = Class.forName(entity + name.substring(0, name.length() - 11));
            if (clazz == null)
                System.out.println(name);

            replace(mapper, clazz);
            replace(xml, clazz);
            count++;
        }


        System.out.println("替换成功，共计[" + count * 2 + "]个文件。");
    }

    private static void replace(File file, Class clazz) throws Exception {
        String text = FileUtils.read(file);
        text = text.replaceAll("ByPrimaryKey", "");
        text = text.replaceAll("ByExampleSelective", "");
        text = text.replaceAll("selectByExample", "find");
        text = text.replaceAll("updateById", "update");
        text = text.replaceAll(" select", " get");

        if (file.getName().endsWith("xml")) {
            text = text.replaceAll("</select>", "</select>\n\n" + SQLGenerator.find(clazz, "e.") + "\n");
        } else {
            String name = clazz.getSimpleName();
            text = text.replaceAll("\\{", "\\{\n\n" + name + " find(@Param(\"e\") " + name + " entity);\n");
        }

        FileUtils.write(file, text);
    }
}
